/*
 * @Description: 新增规则弹窗
 * @Author: Rfan
 * @Date: 2022-04-06 16:19:54
 * @LastEditTime: 2022-05-24 19:34:27
 */

import { useCallback, useEffect } from 'react';
import { Button, Modal } from 'antd';
import type { FC } from 'react';
import ConditionWrap from './components/ConditionWrap';
import OperateWrap from './components/OperateWrap';
import {
  ExpGeneratorDialogContextProvider,
  useExpGeneratorDialogContext
} from './contexts/ExpGeneratorDialogContext';
import type { ICommonDialog } from '@/interfaces/global';

export type TScopeType = {
  atCode: number;
  atType: number;
  fondsId: number;
  archiveTypeId: number;
  level: number[];
};

export interface IExpGeneratorDialogProps extends ICommonDialog {
  // 请求元数据列表需要的参数
  scope: TScopeType;
}

const ExpGeneratorDialogComp: FC<IExpGeneratorDialogProps> = (props) => {
  console.log('ExpGeneratorDialogComp', props.visible);

  const { visible, onClose, scope } = props;
  const { conditionList, getFieldList, resetDialog } = useExpGeneratorDialogContext();

  const memoizedClose = useCallback(
    (condition?: string, scopes?: TScopeType) => onClose(condition, scopes),
    []
  );

  useEffect(() => {
    console.log('effect visible', visible);

    if (visible) {
      getFieldList(scope);
    } else {
      resetDialog();
    }
  }, [visible]);

  const onCancel = () => {
    memoizedClose();
  };

  const saveRule = () => {
    const condition = conditionList
      .map((item: any) => {
        if (item.type === 1) {
          return item.value;
        }
        return `${item.field}${item.operator}'${item.operand}'`;
      })
      .join(' ');
    memoizedClose(condition, scope);
  };

  return (
    <Modal
      title="查询条件生产器"
      visible={visible}
      width={800}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          取消
        </Button>,
        <Button key="save" type="primary" onClick={saveRule}>
          保存查询条件
        </Button>
      ]}
    >
      <ConditionWrap />
      <OperateWrap />
    </Modal>
  );
};

const ExpGeneratorDialog = (props: any) => (
  <ExpGeneratorDialogContextProvider>
    <ExpGeneratorDialogComp {...props} />
  </ExpGeneratorDialogContextProvider>
);

export default ExpGeneratorDialog;
